package me.seu.demo.test.hex;

import java.nio.charset.StandardCharsets;

/**
 * 指令返回值构建
 *
 * @author liangfeihu
 * @since 2021/12/21 14:57
 */
public class InstructionResHelper {


    public static byte[] buildInstructionBuf(Integer serverFlag, String content) {
        byte[] bodyBytes = buildContentBuf(serverFlag, content);
        byte bodyLen = (byte) (1 + bodyBytes.length + 2 + 2);
        byte[] union = ByteArrayUtils.union(
                new byte[]{bodyLen},
                new byte[]{(byte) 0x80},
                bodyBytes,
                //new byte[]{0x00, 0x01}
                new byte[]{0x01, 0x31}
        );
        char crc16 = ItuUtil.getCrc16(union, union.length);
        // crc[0]
        byte one = (byte) ((crc16 >> 8) & 0xff);
        // crc[1]
        byte two = (byte) (crc16 & 0xff);

        return ByteArrayUtils.union(
                new byte[]{0x78, 0x78},
                union,
                new byte[]{one, two},
                new byte[]{0x0D, 0x0A}
        );
    }

    private static byte[] buildContentBuf(Integer serverFlag, String content) {
        byte[] flagBytes = ByteArrayUtils.int2fourBytes(serverFlag);
        byte[] contentBytes = content.getBytes(StandardCharsets.US_ASCII);
        byte length = (byte) (4 + contentBytes.length);
        return ByteArrayUtils.union(new byte[]{length}, flagBytes, contentBytes, new byte[]{0x00, 0x02});
    }

    public static void main(String[] args) {
        byte[] serverFlag = new byte[]{0x00, 0x01, 0x00, 0x01};
        int flag = ByteArrayUtils.fourByte2int(serverFlag);
        String content = "RELAY,0#";
        byte[] startPacket = new byte[]{0x78, 0x78, 0x14, (byte) 0x80,
                0x0C, 0x00, 0x01, 0x00, 0x01,
                0x52, 0x45, 0x4C, 0x41, 0x59, 0x2C, 0x30, 0x23, 0x00, 0x02,
                0x01, 0x31, (byte) 0x8A, 0x17, 0x0D, 0x0A};

        // 78781480
        // 0C 00010001
        // 52454C41592C30230002
        // 0131 8A17 0D0A

        // 0x78781480
        // 0C 00010001
        // 52454C41592C30230002
        // 0001 A24C 0D0A

        byte[] instructionBuf = buildInstructionBuf(flag, content);
        System.out.println(ByteUtilTest.byteToHex(instructionBuf));


    }

}
